package org.company.earth.socket;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Set;

public class MyChannelServerSocket {
	
	public void startup() throws IOException {
		Selector selector = Selector.open();
		ServerSocketChannel serverChannel = ServerSocketChannel.open();
		InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(),8089);
		serverChannel.socket().bind(address);
		serverChannel.configureBlocking(false);
		serverChannel.register(selector, SelectionKey.OP_ACCEPT);
		while(true) {
			if(selector.select() > 0) {
				Set<SelectionKey> selectKeys =  selector.selectedKeys();
				Iterator<SelectionKey> it = selectKeys.iterator();
				while(it.hasNext()) {
					SelectionKey selectKey = it.next();
					if(selectKey.isAcceptable()) {
						ServerSocketChannel server = (ServerSocketChannel)selectKey.channel();
						SocketChannel channel = server.accept();
						channel.configureBlocking(false);
						channel.register(selector, SelectionKey.OP_READ);
						System.out.println("connected:" + channel.socket().getRemoteSocketAddress());
					} else if(selectKey.isReadable()) {
						SocketChannel channel = (SocketChannel)selectKey.channel();
						ByteBuffer buf = ByteBuffer.allocate(1024);
						while(channel.read(buf) > 0) {
							buf.flip();
							byte[] dst = new byte[buf.limit()];
							buf.get(dst);
							System.out.println(new String(dst));
						}
						buf.clear();
						buf.put("replay:".getBytes());
						channel.write(buf);
					}
					it.remove();
				}
			}
		}
	}
	
}
